//
//  DnPhotoGallery.m
//  DnPhotoGallery	
//
//  Created by Ngoc on 12/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#import "DnPhotoGallery.h"

@interface DnPhotoGallery (Private)
-(void) setUpWithDefaultValue;
-(void) selectedItemHandler:(id) sender;
-(void) removeEmptyPage;
-(DnPhotoViewCell*) getNewCellFromPath:(NSString*) path;
-(DnPhotoViewPage*) getNewPageWithPath:(NSString*) folderPath;
-(DnPhotoViewPage*) getExistPageWithKey:(NSString*) folderPath;
-(void) addNewItemToPage:(NSString*) folderName newItem:(DnPhotoViewCell*) newItem;
-(void) showMessageBox:(NSString*) title message:(NSString*) message;
-(void) initToolbarsWithMode:(DnPhotoMode) mode animated:(BOOL) animated;
-(void) toolbarButtonSwitchSate;
-(void) saveCurrentImageToLibrary;
@end

@implementation DnPhotoGallery
@synthesize delegate = _delegate, currentPage, currentItem;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
       // [self setUpWithDefaultValue];
    }
    return self;
}
-(void) setUpWithDefaultValue
{
    _delegate = self;
    [self.view removeFromSuperview];
    
    [self reloadData];
}
- (void)dealloc
{
    [super dealloc];
}

//==================================================================================
- (NSInteger)numberOfCellsInPage:(DnPhotoViewPage *)pageView
{
    NSInteger pageIndex = [_galleryPages indexOfObject:pageView];
    NSInteger count = [(NSArray*)[_galleryItems objectAtIndex:pageIndex] count];
    return count;
}
- (DnPhotoViewCell*)pageView:(DnPhotoViewPage *)pageView itemAtIndex:(NSUInteger)index
{
    NSInteger pageIndex = [_galleryPages indexOfObject:pageView];
    NSArray  *itemsOfPage = [(NSArray*) _galleryItems objectAtIndex:pageIndex];
    return [itemsOfPage objectAtIndex:index] ;
}
-(void) currentPageDidChangeInPagingView:(ATPagingView *)pagingView
{
    _currentPageIndex = pagingView.currentPageIndex;
    if (_currentMode == DnPhotoSelectMode) {
        [self toolbarButtonSwitchSate];
    }
}
- (NSInteger)numberOfPagesInPagingView:(ATPagingView *)pagingView
{
    return [_galleryPages count];
}
- (UIView *)viewForPageInPagingView:(ATPagingView *)pagingView atIndex:(NSInteger)index
{
    return [_galleryPages objectAtIndex:index];
}
//==================================================================================
-(void) viewInGalleryHandler:(id) sender
{
    if (!_isInViewGalleryMode && _currentMode == DnPhotoNormalMode) {
        _isInViewGalleryMode = YES;
    NSMutableArray *menuBars = [[NSMutableArray alloc]init ];
    int numberOfMenuItem = [self.delegate numberOfContextMenu];
    for (int i =0; i<numberOfMenuItem; i++) {
        UIMenuItem* menuItem = [self.delegate contextMenu:sender atIndex:i];
        UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithTitle:menuItem.title style:UIBarButtonItemStyleBordered target:self.delegate action:menuItem.action];
        [menuBars addObject:barButton];
        [barButton release];
    }
    _localGallery = [[FGalleryViewController alloc] initWithPhotoSource:self barItems:menuBars];
    _localGallery.startingIndex = _currentItemIndex;
    _localGallery.isVisibleNextAndPreviousButton = NO;
    _localGallery.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    UIBarButtonItem *btn = [[[UIBarButtonItem alloc] initWithTitle:@"Gallery" style:UIBarButtonItemStyleBordered target:self action:@selector(comeBack:)] autorelease];
    [_localGallery.navigationItem setLeftBarButtonItem:btn];
    _navigationController = [[UINavigationController alloc]initWithRootViewController:_localGallery];
    [[SwitchViewController sharedInstance] switchView:self toView:_navigationController];
    [_localGallery release];
    [_navigationController release];
    [menuBars release];
    
    }
}
-(void) deleteImageHandler:(id) sender
{
    if (_currentMode == DnPhotoNormalMode) {
        
    
    [UIView animateWithDuration:1
                     animations:^{_btnDelete.alpha = 0.0;}
                     completion:^(BOOL finished){ 
                         [_btnDelete setHidden:YES];
                     }];
    [UIView animateWithDuration:1
                     animations:^{_btnViewInGallery.alpha = 0.0;}
                     completion:^(BOOL finished){ 
                         [_btnViewInGallery setHidden:YES];
                     }];
    }
    // Perform delete file action
    NSString *folderPath = [self.currentPage.userData objectForKey:@"folderPath"];
    NSString *filePath = [self.currentItem.userData objectForKey:@"filePath"];
    int numberOfFile = [_imageServices numberImageOfFolder:folderPath];
    [_imageServices deleteFiles:[NSArray arrayWithObject:filePath]];
    
    [[_galleryItems objectAtIndex:_currentPageIndex] removeObjectAtIndex:_currentItemIndex];
    if (_currentMode == DnPhotoSelectMode) {
        [self.currentPage deleteItemAtIndex:_currentItemIndex animation:NO];
    }
    else [self.currentPage deleteItemAtIndex:_currentItemIndex animation:YES];
    
    if (numberOfFile==1) {
        [self performSelector:@selector(removeEmptyPage) withObject:nil afterDelay:1.0f];
    }
}
-(void) removeEmptyPage
{

    switch (_currentMode) {
        case DnPhotoNormalMode:
        {
            [_galleryPages removeObjectAtIndex:_currentPageIndex];
            [_galleryItems removeObjectAtIndex:_currentPageIndex];
            if (_currentPageIndex>0) {
                _currentPageIndex-=1;
            }
            break;
        }   
        case DnPhotoSelectMode:
        {
            [_galleryPages removeObjectAtIndex:_selectedPageIndex];
            [_galleryItems removeObjectAtIndex:_selectedPageIndex];
            break;
        }  
    }
    _photoGridView.pagingView.currentPageIndex = _currentPageIndex;
    [_photoGridView reloadData];
}
-(void) comeBack:(id) sender
{
    CGRect currentFrame = self.view.frame;
    [[SwitchViewController sharedInstance] goToPreviousView];
    self.view.frame = currentFrame;
    _isInViewGalleryMode = NO;
}
-(void) selectedItemHandler:(id)sender
{
    UIView *viewSender = ((UIGestureRecognizer*) sender).view;
    if ([viewSender isKindOfClass:[DnPhotoViewCell class]]) {
        DnPhotoViewCell *cell = (DnPhotoViewCell *)viewSender;
        NSNumber* number = (NSNumber*)[cell.userData valueForKey:@"indexItem"];
        _currentItemIndex = [number intValue];
    }
    if (viewSender!=nil && viewSender.superview !=nil) {
        
        switch (_currentMode) {
            case DnPhotoNormalMode:
            {
                if(_btnDelete==nil)
                {
                    _btnDelete = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
                    [_btnDelete setBackgroundImage:kDnPhotoViewCellButtonDeleteBackground forState:UIControlStateNormal];
                    [_btnDelete addTarget:self action:@selector(deleteImageHandler:) forControlEvents:UIControlEventTouchUpInside];
                    
                }
                else [_btnDelete removeFromSuperview];
                
                if(_btnViewInGallery==nil)
                {
                    _btnViewInGallery = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
                    [_btnViewInGallery setBackgroundImage:kDnPhotoViewCellButtonGalleryBackground forState:UIControlStateNormal];
                    [_btnViewInGallery addTarget:self action:@selector(viewInGalleryHandler:) forControlEvents:UIControlEventTouchUpInside];
                }
                else [_btnViewInGallery removeFromSuperview];
                
                int x = viewSender.frame.origin.x-kDnPhotoViewCellButtonSizeWidth/2;
                int y = viewSender.frame.origin.y-kDnPhotoViewCellButtonSizeHeight/2;
                _btnDelete.frame = CGRectMake(x,y , kDnPhotoViewCellButtonSizeWidth, kDnPhotoViewCellButtonSizeHeight);
                _btnViewInGallery.frame = CGRectMake(_btnDelete.frame.origin.x+viewSender.frame.size.width, _btnDelete.frame.origin.y, kDnPhotoViewCellButtonSizeWidth, kDnPhotoViewCellButtonSizeHeight);
                
                _btnViewInGallery.alpha =1.0f;
                [_btnViewInGallery setHidden:NO];
                _btnDelete.alpha =1.0f;
                [_btnDelete setHidden:NO];
                [viewSender.superview addSubview:_btnDelete];
                [viewSender.superview addSubview:_btnViewInGallery];
                
                if ([viewSender.superview isKindOfClass:[UIScrollView class]]) 
                {
                    [((UIScrollView*) viewSender.superview) scrollRectToVisible:CGRectMake(viewSender.frame.origin.x, viewSender.frame.origin.y-kDnPhotoViewCellButtonSizeHeight/2, viewSender.frame.size.width, viewSender.frame.size.height+kDnPhotoViewCellButtonSizeHeight/2+6) animated:YES];
                    
                }
                
                // Show context menu
                [self becomeFirstResponder];
                int numberOfMenuContext =[_delegate numberOfContextMenu];
                UIMenuController *menuCont = [UIMenuController sharedMenuController]; 
                if (menuCont) {
                    [menuCont setMenuVisible:NO animated:YES];
                }
                [menuCont setTargetRect:CGRectMake(viewSender.frame.size.width/2,viewSender.frame.size.height/2, 0, 0) inView:viewSender]; 
                menuCont.arrowDirection = UIMenuControllerArrowUp;
                NSMutableArray *contextMenus = [[NSMutableArray alloc]init ];
                for (int i=0; i<numberOfMenuContext; i++) {
                    [contextMenus addObject:[[_delegate contextMenu:viewSender atIndex:i]retain]];
                } 
                menuCont.menuItems = contextMenus;
                [menuCont setMenuVisible:YES animated:YES];
                [contextMenus release];
                break;
            }   
            case DnPhotoSelectMode:
            {
                if (!_selectedItems) {
                    _selectedItems = [[NSMutableArray alloc] init ];
                }
                if (_selectedPageIndex ==_currentPageIndex || ([_selectedItems count]==0 && _selectedPageIndex !=_currentPageIndex)) {
                    if (_selectedPageIndex!=_currentPageIndex) {
                        _selectedPageIndex = _currentPageIndex;
                    }
                    
                    if ([viewSender isKindOfClass:[DnPhotoViewCell class]]) {
                        DnPhotoViewCell *item = (DnPhotoViewCell*) viewSender;
                        item.isSelected = !item.isSelected;
                        if (item.isSelected) {
                                [_selectedItems addObject:item];
                            
                            if ([_selectedItems count]==1) {
                                _selectedPageIndex = _currentPageIndex;
                                [self toolbarButtonSwitchSate];
                                
                            }
                        }
                        else if([_selectedItems containsObject:item])
                        {
                            [_selectedItems removeObject:item];
                            if ([_selectedItems count]==0) {
                                [self toolbarButtonSwitchSate];
                            }
                        }
                    }
                    
                }
                
                break;
            }  
        }
        
    }
}
-(void) toolbarButtonSwitchSate
{
    for (UIBarButtonItem *item in _bottomToolbar.items) {
        // Paste
        if (item.tag == 777) {
            if ([_selectedItems count]>0 && _selectedPageIndex!=_currentPageIndex) {
                item.enabled = YES;
            }
            else item.enabled = NO;
        }
        else
        {
            if ([_selectedItems count]>0 && _selectedPageIndex ==_currentPageIndex) {
                item.enabled = YES;
            }
            else item.enabled = NO;
        }
    }
}
-(BOOL) canBecomeFirstResponder
{
    return YES;
}
//==================================================================================

-(void) reloadData
{
    _imageServices = [[DnPhotoGalleryServices alloc]init];
    NSArray *folderPaths, *filePaths;
    
    if (_galleryItems!=nil) {
        [_galleryItems removeAllObjects];
    }
    else _galleryItems = [[NSMutableArray alloc]init ];
    
    if (_galleryPages!=nil) {
        [_galleryPages removeAllObjects];
    }
    else _galleryPages = [[NSMutableArray alloc]init];
    
    // Number of page
    folderPaths = [_imageServices foldersInsideGallery];
    
    for (NSString* folder in folderPaths) {
        filePaths = [_imageServices getImagePathsInFolder:folder];
        if ([filePaths count] >0) {
            DnPhotoViewPage *page;
            page = [self getNewPageWithPath:folder];
            NSMutableArray *items = [[[NSMutableArray alloc]init]autorelease];
            for (NSString* file in filePaths) {
                DnPhotoViewCell *item;
                // Example: Folder: Foods, file: abc.jpg =>Foods/abc.jpg
                NSString *path = [folder stringByAppendingPathComponent:file ];
                item = [self getNewCellFromPath:path];
                [items addObject:item ];
            }
            [_galleryItems addObject:items ];
            [_galleryPages addObject:page ];
            
        }
        else [_imageServices deleteFolders:[[NSArray alloc]initWithObjects:folder,nil]];
    }

}
-(DnPhotoViewPage*) getNewPageWithPath:(NSString*) folderPath
{
    DnPhotoViewPage *page;
    page =[[[DnPhotoViewPage alloc] initWithFrame:CGRectMake(0, 0, _photoGridView.frame.size.width, _photoGridView.frame.size.height)]autorelease];
    page.dataSource = self;
    [page.userData setObject:folderPath forKey:@"folderPath"];
    return page;
}
-(DnPhotoViewPage*) getExistPageWithKey:(NSString*) folderPath
{
    if (_galleryPages) {
        for (DnPhotoViewPage *page in _galleryPages) {
            NSString *folder = [page.userData objectForKey:@"folderPath"];
            if ([folder isEqualToString:folderPath]) {
                return page;
            }
        }
    }
    return nil;
}
-(DnPhotoViewCell*) getNewCellFromPath:(NSString*) path
{
    CGSize thumbnailImageSize = CGSizeMake(100, 100);
    DnPhotoViewCell *item;
    item =[[[DnPhotoViewCell alloc]init] autorelease];
    UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectedItemHandler:)]autorelease];
    tapGesture.numberOfTapsRequired =1;
    tapGesture.numberOfTouchesRequired = 1;
    
    UITapGestureRecognizer *doubletapGesture = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewInGalleryHandler:)]autorelease];
    doubletapGesture.numberOfTapsRequired =2;
    doubletapGesture.numberOfTouchesRequired = 1;
    
    [item addGestureRecognizer:tapGesture];
    [item addGestureRecognizer:doubletapGesture];
    item.userInteractionEnabled = YES;
    item.image = [_imageServices getThumbnailImageFromPath:path size:thumbnailImageSize];
    [item.userData setObject:path forKey:@"filePath"];
    return item;
}
//==================================================================================
// FGallery Delegate

- (int)numberOfPhotosForPhotoGallery:(FGalleryViewController*)gallery
{
    //DnPhotoViewPage *page = [_galleryPages objectAtIndex:_currentPageIndex];
    NSArray *items = [_galleryItems objectAtIndex:_currentPageIndex];
    return [items count];   
}
- (FGalleryPhotoSourceType)photoGallery:(FGalleryViewController*)gallery sourceTypeForPhotoAtIndex:(NSUInteger)index
{
    return FGalleryPhotoSourceTypeLocal;
}
- (NSString*)photoGallery:(FGalleryViewController*)gallery filePathForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index
{
    
    NSArray *items = [_galleryItems objectAtIndex:_currentPageIndex];
    DnPhotoViewCell *item = [items objectAtIndex:index];
    NSString *file = [item.userData valueForKey:@"filePath"];
    NSString * fullPath = [[_imageServices galleryPath] stringByAppendingPathComponent:file] ;
    //[_imageServices release];
    return fullPath;
}
//- (NSString*)photoGallery:(FGalleryViewController*)gallery captionForPhotoAtIndex:(NSUInteger)index
//{
//    
//}
// the photosource must implement one of these methods depending on which FGalleryPhotoSourceType is specified 

//- (NSString*)photoGallery:(FGalleryViewController*)gallery urlForPhotoSize:(FGalleryPhotoSize)size atIndex:(NSUInteger)index
//{
//    
//}

//==================================================================================
-(UIMenuItem*) contextMenu:(UIView*) view atIndex:(NSInteger) index
{
    UIMenuItem *menuItem;
    switch (index) {
        case 0:
        {
            menuItem = [[UIMenuItem alloc]  initWithTitle:@"Edit" action:@selector(viewInGalleryHandler:)];
            break;
        }   
        case 1:
        {
            menuItem = [[UIMenuItem alloc]  initWithTitle:@"Draw" action:@selector(viewInGalleryHandler:)];
            
            break;
        }  
        case 2:
        {
            menuItem = [[UIMenuItem alloc]  initWithTitle:@"Share" action:@selector(viewInGalleryHandler:)];
            
            break;
        }  
        case 3:
        {
            menuItem = [[UIMenuItem alloc]  initWithTitle:@"Save" action:@selector(saveCurrentImageToLibrary)];
            
            break;
        }  
        default:
            break;
    }
     
    return menuItem;
}
-(NSInteger) numberOfContextMenu
{
    return 4;
}
//==================================================================================
-(DnPhotoViewPage*) getCurrentPage
{
    return (DnPhotoViewPage*) [_galleryPages objectAtIndex:_currentPageIndex];
}
-(DnPhotoViewCell*) getCurrentItem
{
    return (DnPhotoViewCell*) [[_galleryItems objectAtIndex:_currentPageIndex] objectAtIndex:_currentItemIndex];
}
-(void) addNewItemToPage:(NSString*) folderName newItem:(DnPhotoViewCell*) newItem
{
    NSInteger pageIndex =0;
    DnPhotoViewPage *page = [self getExistPageWithKey:folderName];
    if (page==nil) {
        page = [self getNewPageWithPath:folderName];
        [_galleryPages addObject:page];
        [_galleryItems addObject:[NSMutableArray arrayWithObject:newItem]];
        pageIndex = [_galleryPages indexOfObject:page];
    }
    else
    {
        pageIndex = [_galleryPages indexOfObject:page];
        NSMutableArray *items = [_galleryItems objectAtIndex:pageIndex];
        [items addObject:newItem];
    }
    [page reloadData];
    _photoGridView.pagingView.currentPageIndex  = pageIndex;
    _currentPageIndex = pageIndex;
    _currentItemIndex =0;
    [_photoGridView.pagingView reloadData];
}
-(void) showMessageBox:(NSString*) title message:(NSString*) message
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show ];
    [alert release];
}
//==================================================================================
-(IBAction) addImageFromLibrary:(id)sender
{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]init];
    pickerController.delegate = self;
    switch ([sender tag]) {
        // get image from library    
        case 0:
        {
            pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            _isCameraOn = NO;
            break;
        }
        //take one,... picture
        case 1:
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
            
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            _isCameraOn = YES;
            }
            else
            {
                [self showMessageBox:@"Message" message:@"Camera isn't avaiable!"];

                return;
            }
            break;
        }
    }
    [self presentModalViewController:pickerController animated:YES];
    [pickerController release];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    NSString *folderName;
    NSString *filePath;
   // NSInteger pageIndex =0;
    
    if (!_isCameraOn) {
        folderName = @"DnLibrary";
        //[[picker parentViewController] dismissModalViewControllerAnimated:YES];
    }
    else
    {
        folderName = @"DnCamera";
        //[[picker parentViewController] dismissModalViewControllerAnimated:YES];
    }
    filePath = [_imageServices saveImage:image toFolderName:folderName];
    if ([filePath length]>0) {
        NSString *fileName = [filePath lastPathComponent];
        NSString *path = [folderName stringByAppendingPathComponent:fileName];
        DnPhotoViewCell *newItem = [self getNewCellFromPath:path];
        [self addNewItemToPage:folderName newItem:newItem];
    }
    

}
-(IBAction) saveAllImageToLibrary:(id) sender
{
    DnPhotoViewPage *page = [self getCurrentPage];
    //NSString *folderName = [page.userData objectForKey:@"folderPath"];
    NSInteger numberItems = [self numberOfCellsInPage:page];
    NSString *filePath;
    NSMutableArray *images;
    images = [[NSMutableArray alloc]init ];
    for (int i =0; i<numberItems; i++) {
        DnPhotoViewCell *item = [[_galleryItems objectAtIndex:_currentPageIndex]objectAtIndex:i];
        filePath = [item.userData objectForKey:@"filePath"];
        
        filePath = [[_imageServices galleryPath] stringByAppendingPathComponent:filePath];// full Path
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        if (image) {
            [images addObject: image];    
        }
    }
    [_imageServices saveImagesToLibrary:images];
    [self showMessageBox:@"Save All" message:@"All done!"];
}
-(void) saveCurrentImageToLibrary
{
    NSString *filePath;
    DnPhotoViewCell *item = [[_galleryItems objectAtIndex:_currentPageIndex]objectAtIndex:_currentItemIndex];
    filePath = [item.userData objectForKey:@"filePath"];
    filePath = [[_imageServices galleryPath] stringByAppendingPathComponent:filePath];
    [_imageServices saveImagesToLibrary:[NSArray arrayWithObject:[UIImage imageWithContentsOfFile:filePath]]];
    [self showMessageBox:@"Save" message:@"Done!"];
}
//==================================================================================
// Toolbar
-(void) changeToEditMode:(id) sender
{
    if (_btnDelete) {
        [_btnDelete setHidden:YES];
    }
    if (_btnViewInGallery) {
        [_btnViewInGallery setHidden:YES];
    }
    [self initToolbarsWithMode:DnPhotoSelectMode animated:YES];
    _currentMode = DnPhotoSelectMode;
    _selectedPageIndex =_currentPageIndex;
}
-(void) changeToNormalMode:(id) sender
{
    if (_btnDelete) {
        [_btnDelete setHidden:NO];
    }
    if (_btnViewInGallery) {
        [_btnViewInGallery setHidden:NO];
    }
    if (_selectedItems) {
        for (DnPhotoViewCell *item in _selectedItems) {
            if (item.isSelected) {
                item.isSelected = NO;
            }
        }
    }
    [self initToolbarsWithMode:DnPhotoNormalMode animated:YES];
    _currentMode = DnPhotoNormalMode;
}
-(NSArray*) getTopToolbarItems:(DnPhotoMode) mode
{
    NSMutableArray *array = [[NSMutableArray alloc]init ];
    switch (mode) {
        case DnPhotoNormalMode:
        {
            UIBarButtonItem *selectAll = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize target:self action:@selector(saveAllImageToLibrary:)];
            UIBarButtonItem *editMode = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(changeToEditMode:)];
            
            UIBarButtonItem *fixDistance = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            [array addObject:selectAll];
            [array addObject:editMode];
            [array insertObject:fixDistance atIndex:1];
            [selectAll release];
            [editMode release];
            [fixDistance release];
            break;
        }       
        case DnPhotoSelectMode:
        {
            UIBarButtonItem *cancel = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(changeToNormalMode:)];
            UIBarButtonItem *fixDistance = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            
            [array addObject:cancel];
            [array insertObject:fixDistance atIndex:0];
            [cancel release];
            [fixDistance release];
            break;
        }  
    }
    return array;
}	
-(void) barButtonDeleteHandler:(id)sender
{
    for (DnPhotoViewCell *item in _selectedItems) {
        NSInteger index = [[_galleryItems objectAtIndex:_currentPageIndex]indexOfObject:item];
        _currentItemIndex = index;
        [self deleteImageHandler:nil];
    }
    [_selectedItems removeAllObjects];
}
-(void) barButtonCutHandler:(id)sender
{
    _isCutAction = YES;
    _isCopyAction = NO;
}
-(void) barButtonCopyHandler:(id)sender
{
    _isCutAction = NO;
    _isCopyAction = YES;
}
-(void) barButtonPasteHandler:(id)sender
{
    DnPhotoViewPage *selectedPage = [_galleryPages objectAtIndex:_selectedPageIndex];
    NSString *selectedFolder = [selectedPage.userData   objectForKey:@"folderPath"];
    NSString *folderPath = [self.currentPage.userData objectForKey:@"folderPath"];
    NSString *filePath;
    int numberOfFile;
    NSInteger itemIndex=0;
   // NSMutableArray *files = [[NSMutableArray alloc]init ];
    NSString *newFilePath;
    for (DnPhotoViewCell *item in _selectedItems) {
        itemIndex = [[_galleryItems objectAtIndex:_selectedPageIndex]indexOfObject:item];
        filePath = [item.userData objectForKey:@"filePath"];
        newFilePath = [filePath lastPathComponent];
        newFilePath = [folderPath stringByAppendingPathComponent:newFilePath];
        item.isSelected = NO;
        if (_isCutAction) {
            [selectedPage deleteItemAtIndex:itemIndex animation:NO];
            NSMutableArray *files = [[NSMutableArray alloc]init];
            [files addObject:[item.userData objectForKey:@"filePath"]];
            [_imageServices moveFiles:files toFolder:folderPath];
            [files release];
            
            [[_galleryItems objectAtIndex:_selectedPageIndex] removeObjectAtIndex:itemIndex];
            [item.userData setValue:newFilePath forKey:@"filePath"];
            [self addNewItemToPage:folderPath newItem:item];
            if ([selectedPage numberOfItems]==0) {
                [self removeEmptyPage];
            }
        }
        else if(_isCopyAction)
        {
//            if (item.isSelected) {
//                item.isSelected = NO;
//            }
            [_imageServices copyFiles:[NSArray arrayWithObject:filePath ] toFolder:folderPath];
                DnPhotoViewCell *newCell = [self getNewCellFromPath:newFilePath];
                [self addNewItemToPage:folderPath newItem:newCell];
        }
    }
    if (_isCutAction) {
        numberOfFile = [_imageServices numberImageOfFolder:selectedFolder];
        if (numberOfFile==1) {
        [self performSelector:@selector(removeEmptyPage) withObject:nil afterDelay:1.0f];
        }
    }
    _isCutAction = NO;
    _isCopyAction = NO;
    
    [_selectedItems removeAllObjects];
    [self toolbarButtonSwitchSate];
}
-(UIButton*) getToolbarButtonWithTitle:(NSString*) title imageName:(NSString*) imageName selector:(SEL) selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:title forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12.0f];
    [button.layer setCornerRadius:4.0f];
    [button.layer setMasksToBounds:YES];
    [button.layer setBorderWidth:1.0f];
    [button.layer setBorderColor: [[UIColor grayColor] CGColor]];
    button.frame=CGRectMake(0.0, 0.0, 60.0, 30.0);
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    return  button;
}
-(NSArray *) getBottomToolbarItems:(DnPhotoMode) mode
{
    NSMutableArray *array = [[NSMutableArray alloc]init ];
    switch (mode) {
        case DnPhotoNormalMode:
        {
            UIBarButtonItem *camera = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(addImageFromLibrary:)];
            camera.tag =1;
            UIBarButtonItem *library = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addImageFromLibrary:)];
            
            UIBarButtonItem *fixDistance = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
            [array addObject:camera];
            [array addObject:library];
            [array insertObject:fixDistance atIndex:1];
            [camera release];
            [library release];
            [fixDistance release];
            break;
        }       
        case DnPhotoSelectMode:
        {
            UIBarButtonItem* delete = [[UIBarButtonItem alloc] initWithCustomView:[self getToolbarButtonWithTitle:@"Delete" imageName:@"delete_item_icon.png" selector:@selector(barButtonDeleteHandler:)]];
            UIBarButtonItem* cut = [[UIBarButtonItem alloc] initWithCustomView:[self getToolbarButtonWithTitle:@"Cut" imageName:@"normal_barBtn.png" selector:@selector(barButtonCutHandler:)]];
            UIBarButtonItem* copy = [[UIBarButtonItem alloc] initWithCustomView:[self getToolbarButtonWithTitle:@"Copy" imageName:@"normal_barBtn.png" selector:@selector(barButtonCopyHandler:)]];
            UIBarButtonItem* paste = [[UIBarButtonItem alloc] initWithCustomView:[self getToolbarButtonWithTitle:@"Paste" imageName:@"normal_barBtn.png" selector:@selector(barButtonPasteHandler:)]];
            delete.width = cut.width = copy.width = paste.width = 68;
            delete.enabled = NO;
            cut.enabled = NO;
            copy.enabled = NO;
            paste.enabled = NO;
            paste.tag = 777;
            
            
            [array addObject:paste];
            [array addObject:cut];
            [array addObject:copy];
            [array addObject:delete];
            break;
        }  
    }
    return array;
}

-(void) initToolbarsWithMode:(DnPhotoMode) mode animated:(BOOL) animated
{
    [_topToolbar setItems:[self getTopToolbarItems:mode] animated:animated];
    [_bottomToolbar setItems:[self getBottomToolbarItems:mode] animated:animated];
//    if (mode == DnPhotoSelectMode) {
//        _selectedPageIndex = _currentPageIndex;
//    }
}
//==================================================================================

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    if (_photoGridView==nil) {
        [self setUpWithDefaultValue];
        _photoGridView = [[[DnPhotoGridView alloc] initWithFrame:CGRectMake(5, 45, 310, 370)]autorelease];
        //_photoGridView.delegate = self;
        _photoGridView.pagingView.delegate = self;
        _photoGridView.datasource = self;
        [self.view addSubview:_photoGridView];
        [self initToolbarsWithMode:DnPhotoNormalMode animated:NO];
    }

}

- (void)viewDidUnload
{
    _photoGridView = nil;
    [_imageServices release];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if(_photoGridView.pagingView.pageCount ==0)
    [_photoGridView.pagingView reloadData];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
@end
